import {
  saveInitAppointSource,
  saveRecord,
  saveRecordQuerySubmitVerify,
} from '@/services/api/api-assess-week-emphasize-record';
import { CheckCircleOutlined, CheckCircleTwoTone } from '@ant-design/icons';
import {
  ModalForm,
  ProFormCascader,
  ProFormDatePicker,
  ProFormDigit,
  ProFormGroup,
  ProFormRadio,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Alert, Button, Divider, message, Spin, Tag } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import UploadDragger from '../components/UploadDragger';
import DetailRecord from './DetailRecord';

interface AddAppointSourceProps {
  onRefurbish: () => void;
}

const AddAppointSource: React.FC<AddAppointSourceProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  /**
   * 提交窗口
   */
  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 初始化Cascader数据
   */

  const [appointSources, setAppointSourcesState] = useState<any>();

  /**
   * 选择 Cascader数据 来源
   */
  const [selectAppointSource, setSelectAppointSourceState] = useState<any>();

  /**
   *  查询提交
   */
  const [querySubmitParamAppointSourceId, setQuerySubmitParamAppointSourceIdState] =
    useState<string>();
  const [querySubmitParamReportType, setQuerySubmitParamReportTypeState] = useState<string>();
  const [querySubmitParamReleaseDate, setQuerySubmitParamReleaseDateState] = useState<string>();

  /**
   * 查询提交状态
   * 0 默认
   * 1 可提交
   * 2 不可提交有占用
   */
  const [querySubmitVerifyState, setQuerySubmitStateState] =
    useState<AssessWeekEmphasizeRecordData.RecordQuerySubmitVerify>();

  /**
   * 预备Cascader结构数据
   * @param data
   */
  function readyCascaderData(data: AssessWeekEmphasizeAppointSourceData.TreeAppointSource[]): any {
    const cascaderData = new Array();
    if (data) {
      data.forEach((val) => {
        cascaderData.push({
          label: val.name,
          value: val.id,
          describes: val.describes,
          channelName: val.channelName,
          children: readyCascaderData(
            val.children as AssessWeekEmphasizeAppointSourceData.TreeAppointSource[],
          ),
        });
      });
    }
    return cascaderData;
  }

  /**
   * 加载来源详情
   * @param key
   */
  const loadSourceData = async () => {
    try {
      const response = await saveInitAppointSource();
      if (response.code === 0) {
        const cascaderData = readyCascaderData(response.data);
        setAppointSourcesState(cascaderData);
      }
    } catch (error) {}
  };

  const verificationSubmit = (values: any) => {
    if (
      !(values.appointSourceCascaderIds !== undefined && values.appointSourceCascaderIds.length > 0)
    ) {
      message.warning('请选择来源');
      return false;
    }

    if (values.releaseDate === undefined) {
      message.warning('请选择日期');
      return false;
    }

    if (!(values.name !== undefined && values.name.length > 0)) {
      message.warning('请输入标题');
      return false;
    }

    if (
      selectAppointSource.channelName == '微信公众号' ||
      selectAppointSource.channelName == '微博' ||
      selectAppointSource.channelName == '今日头条'
    ) {
      if (!(values.dataReadCount !== undefined && values.dataReadCount > 0)) {
        message.warning('请填写阅读量');
        return false;
      }
    } else {
      if (!(values.dataPlayCount !== undefined && values.dataPlayCount > 0)) {
        message.warning('请填写播放量');
        return false;
      }
    }

    if (!(values.dataLikeCount !== undefined && values.dataLikeCount > 0)) {
      message.warning('请填写点赞量');
      return false;
    }
    if (!(values.dataCollectCount !== undefined && values.dataCollectCount > 0)) {
      message.warning('请填写转发量');
      return false;
    }

    return true;
  };

  /**
   * 加载来源详情
   * @param key
   */
  const loadSaveRecordVerify = async () => {
    if (
      querySubmitParamAppointSourceId &&
      querySubmitParamReportType &&
      querySubmitParamReleaseDate
    ) {
      try {
        const response = await saveRecordQuerySubmitVerify({
          appointSourceId: querySubmitParamAppointSourceId,
          reportType: querySubmitParamReportType,
          releaseDate: querySubmitParamReleaseDate,
        });
        if (response.code === 0) {
          const data = response.data;
          setQuerySubmitStateState(data);
        } else {
          setQuerySubmitStateState(undefined);
        }
      } catch (error) {}
    }
  };

  useEffect(() => {
    loadSaveRecordVerify();
  }, [querySubmitParamAppointSourceId]);

  useEffect(() => {
    loadSaveRecordVerify();
  }, [querySubmitParamReportType]);

  useEffect(() => {
    loadSaveRecordVerify();
  }, [querySubmitParamReleaseDate]);

  return (
    <DrawerForm
      key="add_assess_emphasize_record_drawer_form"
      title={'添加重要稿件'}
      drawerProps={{
        width: 750,
        maskClosable: false,
        destroyOnClose: true,
      }}
      layout="horizontal"
      formRef={formRef}
      trigger={<Button type="primary">添加重要稿件</Button>}
      initialValues={{}}
      onOpenChange={(visible) => {
        if (visible) {
          setQuerySubmitStateState(undefined);

          setQuerySubmitParamAppointSourceIdState(undefined);
          setQuerySubmitParamReportTypeState(undefined);
          setQuerySubmitParamReleaseDateState(undefined);

          loadSourceData();
        } else {
          setSelectAppointSourceState(undefined);
          setQuerySubmitStateState(undefined);

          setQuerySubmitParamAppointSourceIdState(undefined);
          setQuerySubmitParamReportTypeState(undefined);
          setQuerySubmitParamReleaseDateState(undefined);
        }
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              hidden={
                !(
                  selectAppointSource !== undefined &&
                  querySubmitParamAppointSourceId &&
                  querySubmitParamReportType &&
                  querySubmitParamReleaseDate &&
                  querySubmitVerifyState != undefined &&
                  querySubmitVerifyState.isVerify == 1
                )
              }
              key="button_release_state_discard"
              icon={<CheckCircleOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                const values = formRef.current?.getFieldsValue();

                if (!verificationSubmit(values)) {
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_release_state_discard'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async (values) => {
                props.submit();
                return true;
              }}
            />,
          ];
        },
      }}
      onChange={(values: any) => {
        console.log('====', values);
      }}
      onFinish={async (values) => {
        if (!verificationSubmit(values)) {
          return false;
        }
        values.appointSourceId =
          values.appointSourceCascaderIds[values.appointSourceCascaderIds.length - 1].split('-')[
            values.appointSourceCascaderIds.length - 1
          ];

        values.releaseTime = values.releaseDate;

        const response = await saveRecord({
          ...values,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={appointSources === undefined}
      >
        <>
          <Alert
            message="每周报的重点作品，要有好报道、好评论、好创意报道三个分类"
            type="warning"
            showIcon
            style={{
              marginBottom: '18px',
            }}
          />
          <ProFormCascader
            width="xl"
            name="appointSourceCascaderIds"
            label={
              <>
                <span
                  style={{
                    color: '#ff4d4f',
                    paddingRight: 4,
                  }}
                >
                  *
                </span>
                平台账号
              </>
            }
            extra={'如没有账号请联系 房一：13220207320'}
            fieldProps={{
              displayRender: (labels: string[], selectedOptions?: any[]) => {
                return labels.map((label, i) => {
                  if (selectedOptions) {
                    const option = selectedOptions[i];
                    if (i === labels.length - 1) {
                      setSelectAppointSourceState(option);
                      return <span key={option.value}>{label}</span>;
                    }
                    return <span key={option.value}>{label} / </span>;
                  } else {
                    return '';
                  }
                });
              },
              options: appointSources,
              allowClear: true,
              onChange(value: any, selectedOptions: any) {
                if (value) {
                  setQuerySubmitParamAppointSourceIdState(
                    value[value.length - 1].split('-')[value.length - 1],
                  );
                } else {
                  setQuerySubmitParamAppointSourceIdState(undefined);
                }
              },
              onClear() {
                setQuerySubmitParamAppointSourceIdState(undefined);
              },
            }}
          />
          <ProFormRadio.Group
            name="reportType"
            label={
              <>
                <span
                  style={{
                    color: '#ff4d4f',
                    paddingRight: 4,
                  }}
                >
                  *
                </span>
                报道类型
              </>
            }
            radioType="button"
            options={[
              {
                label: '好报道',
                value: '1',
              },
              {
                label: '好评论',
                value: '2',
              },
              {
                label: '好创意报道',
                value: '3',
              },
            ]}
            fieldProps={{
              buttonStyle: 'solid',
              onChange(e) {
                setQuerySubmitParamReportTypeState(e.target.value);
              },
            }}
          />
          <ProFormDatePicker
            width="md"
            name="releaseDate"
            label={
              <>
                <span
                  style={{
                    color: '#ff4d4f',
                    paddingRight: 4,
                  }}
                >
                  *
                </span>
                发布日期
              </>
            }
            // extra={
            //   <>
            //     选择范围 {dayjs(releaseTimes[0]).format('YYYY/MM/DD')} -
            //     {dayjs(releaseTimes[1]).format('YYYY/MM/DD')}
            //   </>
            // }
            fieldProps={{
              format: 'YYYY-MM-DD',
              allowClear: true,
              maxDate: dayjs().endOf('day'),
              onChange(date, dateString) {
                if (dateString) {
                  setQuerySubmitParamReleaseDateState(dateString + ' 00:00:00');
                } else {
                  setQuerySubmitParamReleaseDateState(undefined);
                }
              },
              showToday: false,
            }}
          />
          {selectAppointSource !== undefined &&
            querySubmitParamAppointSourceId &&
            querySubmitParamReportType &&
            querySubmitParamReleaseDate && (
              <>
                {querySubmitVerifyState != undefined && querySubmitVerifyState.isVerify == 1 && (
                  <>
                    <Divider
                      orientation="left"
                      style={{
                        fontSize: 14,
                        fontWeight: 'bold',
                      }}
                    >
                      基础数据
                    </Divider>
                    <ProFormTextArea
                      width="xl"
                      name="name"
                      label={
                        <>
                          <span
                            style={{
                              color: '#ff4d4f',
                              paddingRight: 4,
                            }}
                          >
                            *
                          </span>
                          标题
                        </>
                      }
                      fieldProps={{
                        showCount: true,
                        allowClear: true,
                        rows: 2,
                        count: { show: true, max: 100 },
                        style: { resize: 'none' },
                      }}
                    />
                    <div
                      style={{
                        width: 552,
                        marginLeft: 52.05,
                        marginBottom: 25,
                      }}
                    >
                      <Alert
                        message="为保证记录被正确采纳，请尽量填写相关信息，包括链接、附件、备注"
                        type="warning"
                        showIcon
                      />
                    </div>
                    <ProFormTextArea
                      width="xl"
                      name="url"
                      hidden={
                        !(
                          selectAppointSource.channelName == '微信公众号' ||
                          selectAppointSource.channelName == '微信视频号' ||
                          selectAppointSource.channelName == '微博' ||
                          selectAppointSource.channelName == '抖音' ||
                          selectAppointSource.channelName == '今日头条' ||
                          selectAppointSource.channelName == '快手' ||
                          selectAppointSource.channelName == '哔哩哔哩'
                        )
                      }
                      label={
                        <>
                          <span
                            style={{
                              color: '#ff4d4f',
                              paddingRight: 4,
                            }}
                          >
                            *
                          </span>
                          链接
                        </>
                      }
                      fieldProps={{
                        showCount: true,
                        allowClear: true,
                        rows: 3,
                        count: { show: true, max: 5000 },
                        style: { resize: 'none' },
                      }}
                    />
                    <FormItem
                      name="attachments"
                      label={
                        <span
                          style={{
                            marginLeft: 11,
                          }}
                        >
                          附件
                        </span>
                      }
                    >
                      <UploadDragger
                        dragger={true}
                        onPreview={(file) => {}}
                        access={{
                          isPicture: access.传播质效x上报,
                          isVideo: access.传播质效x上报,
                          isOffice: access.传播质效x上报,
                          isOther: access.传播质效x上报,
                        }}
                        url="/assess/week/emphasize/attachment/save"
                        maxCount={10}
                      />
                    </FormItem>
                    <Divider
                      orientation="left"
                      style={{
                        fontSize: 14,
                        fontWeight: 'bold',
                      }}
                    >
                      互动数据
                    </Divider>
                    <ProFormGroup>
                      <ProFormDigit
                        label={
                          <>
                            <span
                              style={{
                                color: '#ff4d4f',
                                paddingRight: 4,
                              }}
                            >
                              *
                            </span>
                            阅读量
                          </>
                        }
                        hidden={
                          !(
                            selectAppointSource.channelName == '微信公众号' ||
                            selectAppointSource.channelName == '微博' ||
                            selectAppointSource.channelName == '今日头条'
                          )
                        }
                        name="dataReadCount"
                        width="xs"
                        min={1}
                        max={selectAppointSource.channelName == '微信公众号' ? 100001 : 99999999}
                        extra={
                          selectAppointSource.channelName == '微信公众号' ? '10万+请添加100001' : ''
                        }
                      />
                    </ProFormGroup>
                    <ProFormGroup>
                      <ProFormDigit
                        label={
                          <>
                            <span
                              style={{
                                color: '#ff4d4f',
                                paddingRight: 4,
                              }}
                            >
                              *
                            </span>
                            播放量
                          </>
                        }
                        hidden={
                          !(
                            selectAppointSource.channelName == '微信视频号' ||
                            selectAppointSource.channelName == '抖音' ||
                            selectAppointSource.channelName == '快手' ||
                            selectAppointSource.channelName == '哔哩哔哩'
                          )
                        }
                        name="dataPlayCount"
                        width="xs"
                        min={1}
                        max={999999999}
                      />
                      <ProFormDigit
                        label={
                          <>
                            <span
                              style={{
                                color: '#ff4d4f',
                                paddingRight: 4,
                              }}
                            >
                              *
                            </span>
                            点赞量
                          </>
                        }
                        name="dataLikeCount"
                        width="xs"
                        min={1}
                        max={9999999}
                      />
                      <ProFormDigit
                        label={
                          <>
                            <span
                              style={{
                                color: '#ff4d4f',
                                paddingRight: 4,
                              }}
                            >
                              *
                            </span>
                            转发量
                          </>
                        }
                        name="dataCollectCount"
                        width="xs"
                        min={1}
                        max={9999999}
                      />
                    </ProFormGroup>
                    <Divider
                      orientation="left"
                      style={{
                        fontSize: 14,
                        fontWeight: 'bold',
                      }}
                    >
                      其他
                    </Divider>
                    <ProFormTextArea
                      width="xl"
                      name="remarks"
                      label={
                        <span
                          style={{
                            marginLeft: 11,
                          }}
                        >
                          备注
                        </span>
                      }
                      fieldProps={{
                        allowClear: true,
                        rows: 3,
                        count: { show: true, max: 5000 },
                      }}
                    />
                  </>
                )}
                {querySubmitVerifyState != undefined && querySubmitVerifyState.isVerify == 0 && (
                  <>
                    <Divider
                      orientation="left"
                      style={{
                        fontSize: 14,
                        fontWeight: 'bold',
                        color: 'red',
                      }}
                    >
                      提示
                    </Divider>
                    {querySubmitVerifyState.records && (
                      <ProTable<AssessWeekEmphasizeRecordData.RecordPage>
                        columns={[
                          {
                            title: (
                              <span
                                style={{
                                  color: '#99a3b7',
                                  fontSize: 12,
                                  textAlign: 'center',
                                  fontWeight: 'normal',
                                }}
                              >
                                平台
                              </span>
                            ),
                            dataIndex: 'datahubChannelName',
                            align: 'center',
                            width: '80px',
                          },
                          {
                            title: (
                              <span
                                style={{
                                  color: '#99a3b7',
                                  fontSize: 12,
                                  textAlign: 'center',
                                  fontWeight: 'normal',
                                }}
                              >
                                账号
                              </span>
                            ),
                            width: '120px',
                            dataIndex: 'datahubSourceName',
                            align: 'center',
                            render: (dom, entity, index, action) => entity.datahubSourceName,
                          },
                          {
                            title: (
                              <span
                                style={{
                                  color: '#99a3b7',
                                  fontSize: 12,
                                  textAlign: 'center',
                                  fontWeight: 'normal',
                                }}
                              >
                                报道类型
                              </span>
                            ),
                            width: '100px',
                            dataIndex: 'dataReportType',
                            align: 'center',
                            render: (dom, entity, index, action) => {
                              let color = '';
                              let label = '';

                              if (entity.dataReportType == 1) {
                                color = 'green';
                                label = '好报道';
                              } else if (entity.dataReportType == 2) {
                                color = 'blue';
                                label = '好评论';
                              } else if (entity.dataReportType == 3) {
                                color = 'orange';
                                label = '好创意报道';
                              }

                              return <Tag color={color}>{label}</Tag>;
                            },
                          },
                          {
                            title: (
                              <span
                                style={{
                                  color: '#99a3b7',
                                  fontSize: 12,
                                  textAlign: 'center',
                                  fontWeight: 'normal',
                                }}
                              >
                                标题
                              </span>
                            ),
                            dataIndex: 'dataName',
                            align: 'center',
                            copyable: true,
                            ellipsis: true,
                            width: '20%',
                            render: (dom, entity, index, action) => (
                              <div
                                style={{
                                  textAlign: 'left',
                                  textOverflow: 'ellipsis',
                                  whiteSpace: 'nowrap',
                                  overflow: 'hidden',
                                }}
                              >
                                <DetailRecord
                                  id={entity.id}
                                  name={entity.dataName}
                                  onRefurbish={function (): void {}}
                                />
                              </div>
                            ),
                          },
                          {
                            title: (
                              <span
                                style={{
                                  color: '#99a3b7',
                                  fontSize: 12,
                                  textAlign: 'center',
                                  fontWeight: 'normal',
                                }}
                              >
                                发布日期
                              </span>
                            ),
                            dataIndex: 'dataReleaseTime',
                            align: 'center',
                            width: '100px',
                            render: (dom, entity, index, action) => {
                              return dayjs(entity.dataReleaseTime).format('YYYY-MM-DD');
                            },
                          },
                        ]}
                        rowKey="id"
                        dataSource={querySubmitVerifyState.records}
                        dateFormatter="id"
                        defaultSize={'small'}
                        pagination={false}
                        search={false}
                        options={{
                          density: false,
                          setting: false,
                        }}
                        ghost
                        headerTitle={
                          <Alert
                            message={
                              <>
                                <div>
                                  已在所选发布日期的一周内（{querySubmitVerifyState.monday}至
                                  {querySubmitVerifyState.sunday}）提交过重要稿件
                                </div>
                              </>
                            }
                            type="warning"
                            showIcon
                          />
                        }
                      />
                    )}
                  </>
                )}
              </>
            )}
        </>
      </Spin>
    </DrawerForm>
  );
};

export default AddAppointSource;
